<?php
/*****************************************************************************
**	Класс:	Общий класс (набор функций)										**
**	Автор:	Dark Dayver														**
**	Версия:	1.0b															**
**	Дата:	25/12-2009														**
*****************************************************************************/
if (IN_P_ENIGMA)
{
	die('HACK!');
}

class work
{
	private $db; // Ссылка на класс работы с БД
	var $config = array(); // Конфигурация
	private $array_rules = array(); // Правила защиты

	function work()
	{
		global $db, $config;
		$this->db = $db;
		unset($config['dbpass']);
		$this->config = $config;

		$this->array_rules = array('http_', '_server', 'delete%20', 'delete ', 'delete-', 'delete(', '(delete',  'drop%20', 'drop ', 'create%20', 'update-', 'update(', '(update', 'insert-', 'insert(', '(insert', 'create ', 'create(', 'create-', '(create', 'update%20', 'update ', 'insert%20', 'insert ', 'select%20', 'select ', 'bulk%20', 'bulk ', 'union%20', 'union ', 'select-', 'select(', '(select', 'union-', '(union', 'union(', 'or%20', 'or ', 'and%20', 'and ', 'exec', '@@', '%22', '"', 'openquery', 'openrowset', 'msdasql', 'sqloledb', 'sysobjects', 'syscolums',  'syslogins', 'sysxlogins', 'char%20', 'char ', 'into%20', 'into ', 'load%20', 'load ', 'msys', 'alert%20', 'alert ', 'eval%20', 'eval ', 'onkeyup', 'x5cx', 'fromcharcode', 'javascript:', 'javascript.', 'vbscript:', 'vbscript.', 'http-equiv', '->', 'expression%20', 'expression ', 'url%20', 'url ', 'innerhtml', 'document.', 'dynsrc', 'jsessionid', 'style%20', 'style ', 'phpsessid', '<applet', '<div', '<emded', '<iframe', '<img', '<meta', '<object', '<script', '<textarea', 'onabort', 'onblur', 'onchange', 'onclick', 'ondblclick', 'ondragdrop', 'onerror',  'onfocus', 'onkeydown', 'onkeypress', 'onload', 'onmouse', 'onmove', 'onreset', 'onresize', 'onselect', 'onsubmit', 'onunload', 'onreadystatechange', 'xmlhttp', 'uname%20', 'uname ',  '%2C', 'union+', 'select+', 'delete+', 'create+', 'bulk+', 'or+', 'and+', 'into+', 'kill+', '+echr', '+chr', 'cmd+', '+1', 'user_password', 'id%20', 'id ', 'ls%20', 'ls ', 'cat%20', 'cat ', 'rm%20', 'rm ', 'kill%20', 'kill ', 'mail%20', 'mail ', 'wget%20', 'wget ', 'wget(', 'pwd%20', 'pwd ', 'objectclass', 'objectcategory', '<!-%20', '<!- ', 'total%20', 'total ', 'http%20request', 'http request', 'phpb8b4f2a0', 'phpinfo', 'php:', 'globals', '%2527', '%27', '\'', 'chr(', 'chr=', 'chr%20', 'chr ', '%20chr', ' chr', 'cmd=', 'cmd%20', 'cmd', '%20cmd', ' cmd', 'rush=', '%20rush', ' rush', 'rush%20', 'rush ', 'union%20', 'union ', '%20union', ' union', 'union(', 'union=', '%20echr', ' echr', 'esystem', 'cp%20', 'cp ', 'cp(', '%20cp', ' cp', 'mdir%20', 'mdir ', '%20mdir', ' mdir', 'mdir(', 'mcd%20', 'mcd ', 'mrd%20', 'mrd ', 'rm%20', 'rm ', '%20mcd', ' mcd', '%20mrd', ' mrd', '%20rm', ' rm', 'mcd(', 'mrd(', 'rm(', 'mcd=', 'mrd=', 'mv%20', 'mv ', 'rmdir%20', 'rmdir ', 'mv(', 'rmdir(', 'chmod(', 'chmod%20', 'chmod ', 'cc%20', 'cc ', '%20chmod', ' chmod', 'chmod(', 'chmod=', 'chown%20', 'chown ', 'chgrp%20', 'chgrp ', 'chown(', 'chgrp(', 'locate%20', 'locate ', 'grep%20', 'grep ', 'locate(', 'grep(', 'diff%20', 'diff ', 'kill%20', 'kill ', 'kill(', 'killall', 'passwd%20', 'passwd ', '%20passwd', ' passwd', 'passwd(', 'telnet%20', 'telnet ', 'vi(', 'vi%20', 'vi ', 'nigga(', '%20nigga', ' nigga', 'nigga%20', 'nigga ', 'fopen', 'fwrite', '%20like', ' like', 'like%20', 'like ', '$_', '$get', '.system', 'http_php', '%20getenv', ' getenv', 'getenv%20', 'getenv ', 'new_password', '/password', 'etc/', '/groups', '/gshadow', 'http_user_agent', 'http_host', 'bin/', 'wget%20', 'wget ', 'uname%5c', 'uname', 'usr', '/chgrp', '=chown', 'usr/bin', 'g%5c', 'g\\', 'bin/python', 'bin/tclsh', 'bin/nasm', 'perl%20', 'perl ', '.pl', 'traceroute%20', 'traceroute ', 'tracert%20', 'tracert ', 'ping%20', 'ping ', '/usr/x11r6/bin/xterm', 'lsof%20', 'lsof ', '/mail', '.conf', 'motd%20', 'motd ', 'http/1.', '.inc.php', 'config.php', 'cgi-', '.eml', 'file%5c://', 'file\:', 'file://', 'window.open', 'img src', 'img%20src', 'img src', '.jsp', 'ftp.', 'xp_enumdsn', 'xp_availablemedia', 'xp_filelist', 'nc.exe', '.htpasswd', 'servlet', '/etc/passwd', '/etc/shadow', 'wwwacl', '~root', '~ftp', '.js', '.jsp', '.history', 'bash_history', '~nobody', 'server-info', 'server-status', '%20reboot', ' reboot', '%20halt', ' halt', '%20powerdown', ' powerdown', '/home/ftp', '=reboot', 'www/', 'init%20', 'init ','=halt', '=powerdown', 'ereg(', 'secure_site', 'chunked', 'org.apache', '/servlet/con', '/robot', 'mod_gzip_status', '.inc', '.system', 'getenv', 'http_', '_php', 'php_', 'phpinfo()', '<?php', '?>', '%3C%3Fphp', '%3F>', 'sql=', '_global', 'global_', 'global[', '_server', 'server_', 'server[', '/modules', 'modules/', 'phpadmin', 'root_path', '_globals', 'globals_', 'globals[', 'iso-8859-1', '?hl=', '%3fhl=', '.exe', '.sh', '%00', rawurldecode('%00'), '_env', '/*', '\\*');

		if (SERVER_NO) $tbl_config = sprintf(TPL_NAME_TBL, SERVER_NO, TBL_CONFIG);
		else $tbl_config = TBL_CONFIG;
		$this->db->select('*', DB_WORK, $tbl_config);
		$this->db->query();
		$result = $this->db->res_arr();
		$this->db->clean();
		if ($result)
		{
			foreach ($result as $tmp)
			{
				$this->config[$tmp['name']] = $tmp['value'];
			}
			if (SERVER_NO)
			{
				$tmp = $this->list_server(SERVER_NO);
				if ($tmp)
				{
					$this->config['title'] = $tmp['name'];
					$this->config['description'] = $tmp['description'];
				}
				else die ('No configured server # ' . SERVER_NO . '!');
			}
		}
		else
		{
			die('Unable to get the settings');
		}
		mb_regex_encoding ('UTF-8');
	}

	function list_server($id = false)
	{
		$this->db->select('*', DB_WORK, TBL_SERVER);
		if ($id) $this->db->where('`id` = ' . $id);
		$this->db->query();
		if ($id) $tmp = $this->db->res_row();
		else $tmp = $this->db->res_arr();
		$this->db->clean();
		if ($tmp) return $tmp;
		else return false;
	}

	function url_check()
	{
		$query_string = strtolower($_SERVER['QUERY_STRING']);

		$hack = false;

		foreach ($this->array_rules as $rules)
		{
			$rules = mb_convert_encoding($rules, 'UTF-8', 'auto');
			$query_string = mb_convert_encoding($query_string, 'UTF-8', 'auto');
			if (mb_ereg(quotemeta($rules), $query_string))
			{
				$_SERVER['QUERY_STRING'] = '';
				$hack = true;
			}
		}
		return $hack;
	}

	function menu()
	{
		global $user;

		$menu_array = array();
		$this->db->select('*', DB_WORK, TBL_MENU);
		if (!$this->config['server_no']) $this->db->where('`in_server` = 0');
		else
		{
			$tmp_where = '';
			if (!$user->id || !$user->permission['admin']) $tmp_where = ' AND `admin` != 1';
			if ($user->id) $this->db->where('`regist` = 1' . $tmp_where);
			else $this->db->where('`guest` = 1' . $tmp_where);
		}
		$this->db->order('id');
		$this->db->query();
		$result = $this->db->res_arr();
		$this->db->clean();
		if ($result)
		{
			$i = 1;
			foreach ($result as $menu)
			{
				$menu_array[$i]['U_URL'] = $menu['url'];
				$menu_array[$i]['L_URL'] = $menu['name'];
				$menu_array[$i]['ID_BUTTON'] = $i;
				$i++;
			}
		}
		return $menu_array;
	}

	function clean_user()
	{
		global $user, $template;
		unset($_SESSION['id'], $user, $template);
		$user = new user();
		$template = new template($work->config['site_url'], $work->config['site_dir'], $user->data['theme'], $user->data['faction']);
	}

	function check_post($field, $isset = false, $empty = false, $regexp = false, $not_zero = false)
	{
		if ($isset && !isset($_POST[$field])) return false;
		else if ($empty && empty($_POST[$field])) return false;
		else return $this->check_field($_POST[$field], $regexp, $not_zero);
	}

	function check_get($field, $isset = false, $empty = false, $regexp = false, $not_zero = false)
	{
		if ($isset && !isset($_GET[$field])) return false;
		else if ($empty && empty($_GET[$field])) return false;
		else return $this->check_field($_GET[$field], $regexp, $not_zero);
	}

	function check_session($field, $isset = false, $empty = false, $regexp = false, $not_zero = false)
	{
		if ($isset && !isset($_SESSION[$field])) return false;
		else if ($empty && empty($_SESSION[$field])) return false;
		else return $this->check_field($_SESSION[$field], $regexp, $not_zero);
	}

	function check_field($field, $regexp = false, $not_zero = false)
	{
		if (empty($field))
		{
			return true;
		}
		$test = true;
		$field_lower = strtolower($field);
		foreach ($this->array_rules as $rules)
		{
			$rules = mb_convert_encoding($rules, 'UTF-8', 'auto');
			$field_lower = mb_convert_encoding($field_lower, 'UTF-8', 'auto');
			if (mb_ereg(quotemeta($rules), $field_lower))
			{
				$test = false;
			}
		}
		if ($regexp)
		{
			$field = mb_convert_encoding($field, 'UTF-8', 'auto');
			if (mb_ereg($regexp, $field)) $test = false;
		}
		if ($not_zero && $field === 0) $test = false;
		return $test;
	}

	function clean_field($field)
	{
		$field = strip_tags($field);
		$field = htmlspecialchars($field);
		return $field;
	}

	function utf8_wordwrap($str, $width = 70, $break = PHP_EOL)
	{
		$str =  preg_split('/([\x20\r\n\t]++|\xc2\xa0)/sSX', $str, -1, PREG_SPLIT_NO_EMPTY);
		$len = 0;
		foreach ($str as $val)
		{
			$val .= ' ';
			$tmp = mb_strlen($val, 'utf-8');
			$len += $tmp;
			if ($len >= $width)
			{
				$return .= $break . $val;
				$len = $tmp;
			}
			else
			{
				$return .= $val;
			}
		}
		return $return;
	}

	function get_factions()
	{
		global $language;

		$faction = false;
		$this->db->select('*', DB_WORK, TBL_FACTION);
		$this->db->query();
		$result = $this->db->res_arr();
		$this->db->clean();
		if ($result)
		{
			$i = 0;
			foreach ($result as $id=>$value)
			{
				$faction[$i] = $value;
				$faction[$i]['name'] = $language->local_faction($faction[$i]['name']);
				$i++;
			}
		}
		return $faction;
	}

	function get_languages()
	{
		$list_languages = array();
		$i = 0;
		if ($dh = opendir($this->config['site_dir'] . 'language/'))
		{
			while (($file = readdir($dh)) !== false)
			{
				if (is_dir($this->config['site_dir'] . 'language/' . $file) && $file != '..' && $file != '.')
				{
					$list_languages[$i]['value'] = $file;
					include($this->config['site_dir'] . 'language/' . $file . '/main.php');
					$list_languages[$i]['name'] = $lang_name;
					$i++;
				}
			}
			closedir($dh);
		}
		return $list_languages;
	}

	function get_themes()
	{
		$list_themes = array();
		$i = 0;
		if ($dh = opendir($this->config['site_dir'] . 'themes/'))
		{
			while (($file = readdir($dh)) !== false)
			{
				if (is_dir($this->config['site_dir'] . 'themes/' . $file) && $file != '..' && $file != '.')
				{
					$list_themes[$i] = $file;
					$i++;
				}
			}
			closedir($dh);
		}
		return $list_themes;
	}

	function gen_captcha()
	{
		$captcha = array();
		$tmp[1] = rand(1, 9);
		$tmp[2] = rand(1, 9);
		$tmp[3] = rand(1, 9);
		$tmp[4] = rand(1, 2);
		$tmp[5] = rand(1, 2);
		$captcha['question'] = '';
		$captcha['answer'] = 0;
		switch ($tmp[5])
		{
			case 1:
				$captcha['question'] = '( ' . $tmp[2] . ' x ' . $tmp[3] . ' )';
				$captcha['answer'] = $tmp[2] * $tmp[3];
				break;
			case 2:
			default:
				$captcha['question'] = '( ' . $tmp[2] . ' + ' . $tmp[3] . ' )';
				$captcha['answer'] = $tmp[2] + $tmp[3];
				break;
		}
		switch ($tmp[4])
		{
			case 1:
				$captcha['question'] = $tmp[1] . ' x ' . $captcha['question'];
				$captcha['answer'] = $tmp[1] * $captcha['answer'];
				break;
			case 2:
			default:
				$captcha['question'] = $tmp[1] . ' + ' . $captcha['question'];
				$captcha['answer'] = $tmp[1] + $captcha['answer'];
				break;
		}
		return $captcha;
	}

	function get_stat($full = false)
	{
		$static = array();
		if (SERVER_NO)
		{
			$tbl['users'] = TBL_USERS;
			$tbl['alliance'] = TBL_ALLIANCE;
			$tbl['alliance_user'] = TBL_ALLIANCE_USER;
			$static = $this->get_stat_server($tbl);
		}
		else
		{
			$list_server = $this->list_server();
			foreach ($list_server as $key=>$value)
			{
				$tbl['users'] = sprintf(TPL_NAME_TBL, $value['id'], 'user');
				$tbl['alliance'] = sprintf(TPL_NAME_TBL, $value['id'], 'alliance');
				$tbl['alliance_user'] = sprintf(TPL_NAME_TBL, $value['id'], 'alliance_user');
				$static[$value['id']] = $this->get_stat_server($tbl);
			}
		}
		return $static;
	}

	function get_stat_server($tbl)
	{
		$static = array();
		$this->db->select('COUNT(*) AS `all_user`', DB_USER, $tbl['users']);
		$this->db->query();
		$result = $this->db->res_row();
		$this->db->clean();
		if ($result) $static['all_user'] = $result['all_user'];
		else $static['all_user'] = 0;
		$this->db->select('COUNT(*) AS `activ_user`', DB_USER, $tbl['users']);
		$this->db->where('`date_last_active` IS NOT NULL AND `date_last_active` >= "' . date('Y-m-d H:i:s', (time() - ($this->config['online_user_last_hour'] * 3600))) . '"');
		$this->db->query();
		$result = $this->db->res_row();
		$this->db->clean();
		if ($result) $static['activ_user'] = $result['activ_user'];
		else $static['activ_user'] = 0;
		$this->db->select('COUNT(*) AS `all_alliance`', DB_USER, $tbl['alliance']);
		$this->db->query();
		$result = $this->db->res_row();
		$this->db->clean();
		if ($result) $static['all_alliance'] = $result['all_alliance'];
		else $static['all_alliance'] = 0;
		$this->db->select('COUNT(*) AS `user_in_alliance`', DB_USER, $tbl['alliance_user']);
		$this->db->query();
		$result = $this->db->res_row();
		$this->db->clean();
		if ($result) $static['user_in_alliance'] = $result['user_in_alliance'];
		else $static['user_in_alliance'] = 0;
		return $static;
	}

	function filt_email($email)
	{
		$email = str_replace('@', '[at]', $email);
		$email = str_replace('.', '[dot]', $email);
		return $email;
	}

	function get_gallery_avatar($id = false)
	{
		if ($id === 0)
		{
			$tmp['id'] = 0;
			$tmp['folder'] = 'user_upload';
			$tmp['name'] = '';
			return $tmp;
		}
		else
		{
			$this->db->select('*', DB_WORK, TBL_GALLERY_AVATAR);
			if ($id) $this->db->where('`id` = ' . $id);
			$this->db->query();
			if ($id) $tmp = $this->db->res_row();
			else $tmp = $this->db->res_arr();
			$this->db->clean();
			if ($tmp) return $tmp;
			else return false;
		}
	}

	function image_attach($full_path, $name_file)
	{
		$size = getimagesize($full_path);
		header("Content-Type: " . $size['mime']);
		header("Content-Disposition: inline; filename=\"" . $name_file . "\"");
		header("Content-Length: " . (string)(filesize($full_path)));
		flush();
		$fh = fopen($full_path, 'rb');
		fpassthru($fh);
		fclose($fh);
		exit();
	}
}
?>
